package web.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.*;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class JdbcUtils {
    private static QueryRunner runner=null;

    static{
        Properties prop = new Properties();
        InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
        try {
            prop.load(is);
            DataSource ds = DruidDataSourceFactory.createDataSource(prop);
            //创建操作对象
            runner = new QueryRunner(ds);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //全查询的通用方法
    public static <T> List<T> selectAll(Class clazz,String sql,Object... args){
        try {
            //使实体类和数据库中的字段保持一致
            BasicRowProcessor basic = new BasicRowProcessor(new GenerousBeanProcessor());
            return runner.query(sql,new BeanListHandler<T>(clazz,basic),args);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //单查询
    public static <T> T selectOne(Class clazz,String sql,Object... args){
        BasicRowProcessor basic = new BasicRowProcessor(new GenerousBeanProcessor());
        try {
           return runner.query(sql,new BeanHandler<T>(clazz,basic),args);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //增删改
    public static int update(String sql,Object... args){
        try {
            return runner.update(sql,args);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    //查询行数
    public static int pageCount(String sql,Object... args)  {
        try {
           return runner.query(sql, new ResultSetHandler<Integer>() {
                @Override
                public Integer handle(ResultSet resultSet) throws SQLException {
                    //查询第一行
                    resultSet.next();
                    //返回第一列的整数值
                    return resultSet.getInt(1);
                }
            },args);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    };

//    //MapToBean
    public static <T> T mapToBean(Class<T> t,Map map){
        T t1=null;
        try {
            t1 = t.newInstance();
            BeanUtils.populate(t1,map);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return t1;
    }

}
